import styles from "./index.module.scss";
import * as echarts from "echarts/core";
import ReactECharts from "echarts-for-react";
import { useState, useRef, useLayoutEffect } from "react";
import {
  createPieOptions,
  createLineOptions,
  createBarOptions,
  createCellBarOptions
} from "./optionConfig";
import { myTheme } from "./theme";

// 统计头部组件
const listItems: Array<any> = [
  {
    id: 1,
    num: 100,
    name: "用户数",
    color: "#00A0E9",
    icon: "icon-user",
    desc: "用户数",
    percent: 0.1,
  },
  {
    id: 2,
    num: 200,
    name: "订单数",
    color: "#FFB800",
    icon: "icon-order",
    desc: "订单数",
    percent: 0.1,
  },
  {
    id: 3,
    num: 300,
    name: "商品数",
    color: "#FF5722",
    icon: "icon-goods",
    desc: "商品数",
    percent: 0.1,
  },
  {
    id: 4,
    num: 400,
    name: "退货数",
    color: "#9933FF",
    icon: "icon-goods",
    desc: "退货数",
    percent: 0.1,
  },
];

// 关键步骤：在组件外部注册主题
echarts.registerTheme("myTheme", myTheme);
export default function Statistics({ ratio = 16 / 7 }) {
  const options = {
    large: true, // 开启大数据优化
    progressive: 200, // 分片加载
    grid: { top: 30, right: 20, bottom: 30, left: 30 },
    xAxis: { data: ["A", "B", "C", "D", "E", "F", "G"] },
    yAxis: {},
    series: [{ type: "bar", data: [5, 20, 36, 10, 25, 26, 55] }],
  };
  const containerRef = useRef<HTMLDivElement>(null);
  const [height, setHeight] = useState(0);

  // 监听容器尺寸变化
  useLayoutEffect(() => {
    if (!containerRef.current) return;
    const updateSize = () => {
      const { width } = containerRef.current?.getBoundingClientRect() ?? {
        width: 0,
      };
      if (width > 0) {
        setHeight(width / ratio);
      }
    };

    updateSize(); // 初始化调用
    const observer = new ResizeObserver((entries) => {
      requestAnimationFrame(() => {
        if (!Array.isArray(entries) || !entries.length) return;
        updateSize();
      });
    });

    observer.observe(containerRef.current);
    return () => observer.disconnect();
  }, [ratio]);

  // 饼状图
  const pieOptions = createPieOptions([
    { value: 1048, name: "Search Engine" },
    { value: 735, name: "Direct" },
    { value: 580, name: "Email" },
    { value: 484, name: "Union Ads" },
    { value: 300, name: "Video Ads" },
  ]);
  const lineOptions = createLineOptions({
    one: [
      { value: 1048, name: "周一" },
      { value: 735, name: "周二" },
      { value: 580, name: "周三" },
      { value: 484, name: "周四" },
      { value: 300, name: "周五" },
      { value: 300, name: "周六" },
      { value: 300, name: "周日" },
    ],
    two: [
      { value: 448, name: "周一" },
      { value: 435, name: "周二" },
      { value: 180, name: "周三" },
      { value: 284, name: "周四" },
      { value: 300, name: "周五" },
      { value: 200, name: "周六" },
      { value: 100, name: "周日" },
    ],
  });

  const doubleBarOptions = createBarOptions({
    one: [
      { value: 1048, name: "Mon" },
      { value: 735, name: "Tue" },
      { value: 580, name: "Wed" },
      { value: 484, name: "Thu" },
      { value: 300, name: "Fri" },
      { value: 300, name: "Sat" },
      { value: 300, name: "Sun" },
    ],
    two: [
      { value: 1048, name: "Mon" },
      { value: 635, name: "Tue" },
      { value: 580, name: "Wed" },
      { value: 284, name: "Thu" },
      { value: 300, name: "Fri" },
      { value: 1200, name: "Sat" },
      { value: 200, name: "Sun" },
    ],
  });
  const singleBarOptions = createBarOptions({
    测试: [
      { value: 448, name: "Mon" },
      { value: 135, name: "Tue" },
      { value: 580, name: "Wed" },
      { value: 484, name: "Thu" },
      { value: 300, name: "Fri" },
      { value: 300, name: "Sat" },
      { value: 300, name: "Sun" },
    ],
  });
  const mixtureOptions = {
    grid: { top: 50, right: 30, bottom: 30, left: 50 },
    legend: {
      top: 10
    },
    tooltip: {},
    dataset: {
      source: [
        ["product", "2015", "2016", "2017"],
        ["Matcha Latte", 43.3, 85.8, 93.7],
        ["Milk Tea", 83.1, 73.4, 55.1],
        ["Cheese Cocoa", 86.4, 65.2, 82.5],
        ["Walnut Brownie", 72.4, 53.9, 39.1],
      ],
    },
    xAxis: { type: "category" },
    yAxis: {},
    // Declare several bar series, each will be mapped
    // to a column of dataset.source by default.
    series: [{ type: "bar" }, { type: "bar" }, { type: "line" }],
  };

  const cellBarOption = createCellBarOptions({
    one: [{
      name: '2023-01',
      value: 100,
    }]
  })
  const echartsRef = useRef(null);
 // 定义饼图点击事件处理函数
  const handlePieChartClick = (params: any) => {
    console.log('饼图点击事件触发', params.data);
    console.log('饼图实例', echartsRef.current);
    // 可以在这里添加点击饼图数据项的业务逻辑
  };
  return (
    <>
      <div className={styles.head}>
        {listItems.map((item) => (
          <div key={item.id} className={styles.headItem}>
            <div className={styles.headItemTitle} style={{ color: item.color }}>
              {item.name}
            </div>
            <div className={styles.headItemNum}> {item.num}</div>
            <div className={styles.headItemDesc}> {item.desc}</div>
          </div>
        ))}
      </div>
      {/* 多个class */}
      <div
        ref={containerRef}
        className={`${styles.echartContent} flex`}
        style={{
          height: `${height}px`,
        }}
      >
        <div className={`${styles.contentRight}`}>
          <div className={styles.echartBox}>
            <ReactECharts
              ref={echartsRef}
              option={pieOptions}
              style={{ height: "100%" }}
              theme="myTheme" // 使用注册的主题
              notMerge={true} // 强制用新 options 完全替换旧配置, 当数据结构发生重大变化时, 会导致图表重新初始化（性能损耗）
              lazyUpdate={true} // 延迟图表更新到浏览器空闲时段, 避免频繁更新导致的性能问题
              onEvents={{
                click: handlePieChartClick, // 当调用 chart.on('click', callback) 时触发
                // 当调用 chart.resize() 或容器尺寸变化时触发// 监听了resize事件
                resize: () => console.log("Chart resized"),
              }}
            />
          </div>
          <div className={styles.echartBox}>
            <ReactECharts
              option={lineOptions}
              style={{ height: "100%" }}
              theme="myTheme"
              notMerge={true} // 强制用新 options 完全替换旧配置, 当数据结构发生重大变化时, 会导致图表重新初始化（性能损耗）
              lazyUpdate={true} // 延迟图表更新到浏览器空闲时段, 避免频繁更新导致的性能问题
              onEvents={{
                resize: () => console.log("Chart resized"),
              }}
            />
          </div>
          <div className={styles.echartBox}>
            <ReactECharts
              option={doubleBarOptions}
              style={{ height: "100%" }}
              theme="myTheme"
              notMerge={true} // 强制用新 options 完全替换旧配置, 当数据结构发生重大变化时, 会导致图表重新初始化（性能损耗）
              lazyUpdate={true} // 延迟图表更新到浏览器空闲时段, 避免频繁更新导致的性能问题
              onEvents={{
                resize: () => console.log("Chart resized"),
                // 点击图例legend
                legendselectchanged: (params: any) => {
                  console.log('图例点击事件触发', params);
                }
              }}
            />
          </div>
        </div>
        <div className={styles.contentCenter}>
          <div className={styles.echartBox}>
            <ReactECharts
              option={mixtureOptions}
              style={{ height: "100%" }}
              theme="myTheme"
              notMerge={true} // 强制用新 options 完全替换旧配置, 当数据结构发生重大变化时, 会导致图表重新初始化（性能损耗）
              lazyUpdate={true} // 延迟图表更新到浏览器空闲时段, 避免频繁更新导致的性能问题
              onEvents={{
                resize: () => console.log("Chart resized"),
              }}
            />
          </div>
          <div className={styles.echartBox}>
            <ReactECharts
              option={cellBarOption}
              style={{ height: "100%" }}
              theme="myTheme"
              notMerge={true} // 强制用新 options 完全替换旧配置, 当数据结构发生重大变化时, 会导致图表重新初始化（性能损耗）
              lazyUpdate={true} // 延迟图表更新到浏览器空闲时段, 避免频繁更新导致的性能问题
              onEvents={{
                resize: () => console.log("Chart resized"),
              }}
            />
          </div>
        </div>
        <div className={styles.contentLeft}>
          <div className={styles.echartBox}>
            <ReactECharts
              option={singleBarOptions}
              style={{ height: "100%" }}
              theme="myTheme"
              notMerge={true} // 强制用新 options 完全替换旧配置, 当数据结构发生重大变化时, 会导致图表重新初始化（性能损耗）
              lazyUpdate={true} // 延迟图表更新到浏览器空闲时段, 避免频繁更新导致的性能问题
              onEvents={{
                resize: () => console.log("Chart resized"),
              }}
            />
          </div>
          <div className={styles.echartBox}>
            <ReactECharts
              option={options}
              style={{ height: "100%" }}
              theme="myTheme"
              notMerge={true} // 强制用新 options 完全替换旧配置, 当数据结构发生重大变化时, 会导致图表重新初始化（性能损耗）
              lazyUpdate={true} // 延迟图表更新到浏览器空闲时段, 避免频繁更新导致的性能问题
              onEvents={{
                resize: () => console.log("Chart resized"),
              }}
            />
          </div>
          <div className={styles.echartBox}>
            <ReactECharts
              option={lineOptions}
              style={{ height: "100%" }}
              theme="myTheme"
              notMerge={true} // 强制用新 options 完全替换旧配置, 当数据结构发生重大变化时, 会导致图表重新初始化（性能损耗）
              lazyUpdate={true} // 延迟图表更新到浏览器空闲时段, 避免频繁更新导致的性能问题
              onEvents={{
                resize: () => console.log("Chart resized"),
              }}
            />
          </div>
        </div>
      </div>
    </>
  );
}
